package callme.ghost.model;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 * 
 * La classe sonnerie permet d'envoyer un train sonnerie en lisant un fichier
 * wav qui se trouve dans le dossier "audio"
 * 
 * @author Anthony
 * 
 */
class Ringing extends Thread {
	private static final int BUFFER = 246000; // 128k
	File soundFile;
	AudioInputStream audioInputStream = null;
	SourceDataLine line = null;
	boolean Stop = false;

	public Ringing() {

	}

	public void run() {

		soundFile = new File("audio", "ring.wav");
		if (!soundFile.exists()) {
			System.err.println("wav file not found ");
			return;
		}
		try {
			audioInputStream = AudioSystem.getAudioInputStream(soundFile);
		} catch (UnsupportedAudioFileException e1) {
			e1.printStackTrace();
			return;
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		AudioFormat audioFormat = audioInputStream.getFormat();

		DataLine.Info info = new DataLine.Info(SourceDataLine.class,
				audioFormat);
		try {
			line = (SourceDataLine) AudioSystem.getLine(info);

			line.open(audioFormat);

		} catch (LineUnavailableException e) {
			e.printStackTrace();
			return;
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		line.start();

		int nBytesRead = 0;
		byte[] abData = new byte[BUFFER];

		try {
			while (nBytesRead != -1) {
				nBytesRead = audioInputStream.read(abData, 0, abData.length);
				if (nBytesRead >= 0) {
					line.write(abData, 0, nBytesRead);
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
			return;
		} finally {

			line.drain();
			line.close();
		}
	}
}